<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------

namespace app\api\logic;

use app\common\logic\LogicBase;
use \tpfcore\Core;
use think\Validate;
use think\Db;

class CashOutLog extends ApiBase
{
    public function getCashOutLog($data = [])
    {
        $member_info = $this->getBaseUserInfo();
        $user_id=$member_info['id'];

        $starttime = empty($data["starttime"])?"":strtotime($data["starttime"]);

        $endtime = empty($data["endtime"])?time():strtotime($data["endtime"]);

        $where['user_id']=$user_id;

        if($starttime){
          $where['addtime'] = ['between',"$starttime,$endtime"];
        }else{
            $where['addtime']=["<=",$endtime];
        }

        $result = Core::loadModel($this->name)->getList([
            "where"=>$where,
            "paginate"=>['rows' => DB_LIST_ROWS],
            "order"=>"addtime desc"
        ]);
        return [0,"success",$result];
    }
    public function addCashOutLog($data=[]){
        if(empty($data['target']) || !in_array($data['target'], ['wechat','alipay','bankcard'])){
            return [40048,"请选择要提现的地方"];
        }
        if(empty($data['cash_data'])){
            return [40048,"请填写数据"];   
        }

        if(empty($data['money']) || !is_numeric($data['money']) || $data['money']<=0 || $data['money']>1000){
            return [40048,"提现金额无效"]; 
        }

        $member_info = $this->getBaseUserInfo();

        //验证自己的可提现金额是否足够
        $userModel = Core::loadModel("User");
        $listUser = $userModel->getOneObject(["id"=>$member_info['id']],"profit");
        if(empty($listUser) || $listUser['profit']<$data['money']){
            return [50055,"可提现金额不足"];
        }

        $validate = \think\Loader::validate($this->name);
        $validate_result = $validate->scene($data['target'])->check($data['cash_data']);
        if (!$validate_result) {
            return [4003, $validate->getError()];
        }
        
        $data['user_id']=$member_info['id'];
        Db::startTrans();
        try{
            $result = Core::loadModel($this->name)->saveObject($data);
            if($result){
                $res = $userModel->where(["id"=>$member_info['id']])->setDec("profit",$data['money']);
                if(!$res){
                    throw new \Exception("扣款失败", 1);
                }
            }else{
                return [40048,"提现失败"];
            }
            Db::commit();
        }catch(\Exception $e){

            Db::rollback();

            return [50055,$e->getMessage()];

        }
        return [0,"申请成功"]; 
    }
}